<!--
 * @Author: c
 * @Date: 2024-02-27 01:27:44
 * @LastEditTime: 2024-03-10 14:05:35
 * @LastEditors: c
 * @Description: 
 * @FilePath: \music-web-admin\src\views\application\music\banner\index.vue
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-names
  name: "Video",
  inheritAttrs: false,
});

import { listArtistOptions } from "@/api/application/artist";
import { VideoQuery, VideoVO } from "@/api/application/video/types";
// import { UploadFileDto } from "@/api/minio/type";

import {
  addBanner,
  deleteBanner,
  getBannerForm,
  listBanners,
  updateBanner,
} from "@/api/application/banner";
import { BannerForm } from "@/api/application/banner/type";
import { listSongOptions } from "@/api/application/song";
import { BannerType } from "@/enums";
import { useAudioStore } from "@/store/modules/audio";
import { OptionType } from "element-plus/es/components/select-v2/src/select.types";
import { storeToRefs } from "pinia";
import { onMounted, reactive, ref } from "vue";
const store = useAudioStore();
const { currentTime, currentTimeStr, lrcData, lrcText } = storeToRefs(store);
const albumBannerFormRef = ref(ElForm);
const bannerFormData = reactive<BannerForm>({
  showEndDate: new Date(),
  showStartDate: new Date(),
  jumpLinkOutput: undefined,
  jumpType: BannerType.Album,
  sort: 0,
  showDate: "",
});
const bannerDialog = reactive({
  title: "",
  visible: false,
});

const queryFormRef = ref(ElForm);

const queryParams = reactive<VideoQuery>({
  pageNum: 1,
  pageSize: 10,
});
const loading = ref(false);
const filterLoading = ref(false);
const dialog = reactive({
  title: "",
  visible: false,
});

const videoList = ref<VideoVO[]>([]);
const artistOptions = ref<OptionType[]>([]);
const songOptions = ref<OptionType[]>([]);
const albumOptions = ref<OptionType[]>([]);
const cateOptions = ref<OptionType[]>([]);
const uploadUrl = ref<string>();

const removeIds = ref([]); // 删除视频ID集合 用于批量删除
const shortcuts = computed(() => {
  return [
    {
      text: "一周",
      value: () => {
        const end = new Date();

        const start = new Date();

        end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: "一个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: "三个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ];
});
const rules = computed(() => {
  return {
    indexDataAddTime: [
      { required: true, message: "请选择上架时间", trigger: "blur" },
    ],
    originalReleaseDate: [
      { required: true, message: "请选择发行时间", trigger: "blur" },
    ],
    videoName: [{ required: true, message: "请输入视频名称", trigger: "blur" }],
  };
});
const total = ref(0); // 数据总数
// 选择表格的行视频ID
const selectedRowVideoId = ref<number | undefined>();

/**
 * 查询
 */
async function handleQuery() {
  // 重置父组件
  loading.value = true;
  try {
    const data = await listBanners(queryParams);

    // videoList.value = data;

    videoList.value = data.list;
    total.value = data.total;
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**行点击事件 */
function onRowClick(row: VideoVO) {
  selectedRowVideoId.value = row.id;
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

async function openDialog(bannerId: number) {
  if (bannerId) {
    const data = await getBannerForm(bannerId);
    Object.assign(bannerFormData, data);
    bannerFormData.showDate = [
      bannerFormData.showStartDate,
      bannerFormData.showEndDate,
    ];
  }

  bannerDialog.visible = true;
  bannerDialog.title = "编辑轮播图";
}

/** 视频保存提交 */
function submitBannerForm() {
  albumBannerFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        if (bannerFormData.id) {
          let showDate = bannerFormData.showDate as any;
          bannerFormData.showStartDate = showDate.at(0) ?? new Date();
          bannerFormData.showEndDate = showDate.at(1) ?? new Date();
          await updateBanner(bannerFormData.id, bannerFormData);
        } else {
          await addBanner(bannerFormData);
        }

        ElMessage.success(`${bannerFormData.id ? "修改" : "新增"}成功`);

        closeBannerDialog();
        handleQuery();
      } catch (error) {
        throw error;
      } finally {
      }
    }
  });
}

/** 删除视频 */
function handleDelete(id?: number) {
  const ids = id ?? removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteBanner(ids);
      ElMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => ElMessage.info("已取消删除"));
}

/**
 * 筛选歌手名称
 * @param query
 */
const filterArtist = async (query: string) => {
  if (query !== "") {
    filterLoading.value = true;
    artistOptions.value = await listArtistOptions({
      keywords: query,
      pageNum: 1,
      pageSize: 10,
    });
    filterLoading.value = false;
  } else {
    artistOptions.value = [];
  }
};

/**
 * 筛选歌曲名称
 * @param query
 */
const filterSong = async (query: string) => {
  if (query !== "") {
    filterLoading.value = true;
    songOptions.value = await listSongOptions({
      songName: query,
      pageNum: 1,
      pageSize: 10,
    });
    filterLoading.value = false;
  } else {
    // songOptions.value = [];
  }
};

/** 关闭弹窗 */
function closeBannerDialog() {
  bannerDialog.visible = false;
  resetBannerForm();
}

/** 重置表单 */
function resetBannerForm() {
  albumBannerFormRef.value.resetFields();
  albumBannerFormRef.value.clearValidate();
}

onMounted(() => {
  handleQuery();
  // MediaInfoFactory().then(() => {
  //   console.log('Loaded');
  // });
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="title">
          <el-input
            v-model="queryParams.videoName"
            placeholder="视频名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><template #icon><i-ep-search /></template>搜索</el-button
          >
          <el-button @click="resetQuery">
            <template #icon><i-ep-refresh /></template>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['sys:video:create']"
          type="success"
          @click="openDialog(0)"
        >
          <template #icon><i-ep-plus /></template>
          新增</el-button
        >
        <el-button
          v-hasPerm="['sys:video:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        :data="videoList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <!-- <el-table-column label="id" align="left" width="50" prop="id" /> -->

        <el-table-column label="标题" width="150" prop="title" />
        <el-table-column label="状态" align="center" width="200">
          <template #default="scope">
            <el-tag v-if="scope.row.outDate" type="info">过期</el-tag>
            <el-tag v-else type="success">进行中</el-tag>
          </template>
        </el-table-column>

        <!-- <el-table-column label="排序" align="center" width="300" prop="sort" /> -->
        <el-table-column
          label="开始时间"
          align="left"
          width="200"
          prop="showStartDate"
        />
        <el-table-column
          label="结束时间"
          align="left"
          width="200"
          prop="showEndDate"
        />
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          min-width="220"
        >
          <template #default="scope">
            <!-- <el-button type="primary" link size="small" @click.stop="openPlayDialog(scope.row.id)">
              <i-ep-plus />播放
            </el-button> -->

            <el-button
              v-hasPerm="['sys:video:update']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:video:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery"
        />
      </template>
    </el-card>

    <!-- 编辑轮播图 -->
    <el-dialog
      v-model="bannerDialog.visible"
      :title="bannerDialog.title"
      destroy-on-close
      append-to-body
      width="800px"
      @close="closeBannerDialog"
      :draggable="true"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="albumBannerFormRef"
        :model="bannerFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="发行日期" prop="pushTime">
          <el-date-picker
            v-model="bannerFormData.showDate"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="bannerFormData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBannerForm">确 定</el-button>
          <el-button @click="closeBannerDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.avatar {
  display: block;
  width: 178px;
  height: 178px;
  object-fit: scale-down;
}

.avatar-cover-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  // cursor: default;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  // pointer-events: none;
  width: 100%;
  height: 100%;
  font-size: 20px;
  color: #fff;
  cursor: pointer;
  background-color: var(--el-overlay-color-lighter);
  opacity: 0;
  transition: opacity var(--el-transition-duration);

  .avatar-icon {
    font-size: 20px;
  }

  .avatar-zoomin-icon {
    margin-right: 15px;
  }
}

.avatar-delete-wrapper {
  position: relative;
  border: 1px dashed gray;

  &:hover {
    .avatar-cover-wrapper {
      opacity: 1;
    }
  }
}

.upload-video {
  // background-color: #000;
  position: relative;
  width: 500px;
  // height: 150px;
  aspect-ratio: 16 / 9;

  .upload-btn {
    width: 500px;
    height: 281.25px;
    aspect-ratio: 16 / 9;
  }
}

.delete-video-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  color: #fff;
}

.el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}
</style>

<style lang="scss">
.play-progress {
  margin-bottom: 15px;
}

.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
